<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="adminId">
        <el-input v-model="queryParams.adminId" :placeholder="$t('iot.enterCustomerName')" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:equipment:add']">{{ $t('common.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['iot:equipment:edit']">{{ $t('common.edit') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:equipment:remove']">{{ $t('common.delete') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:equipment:export']">{{ $t('common.export') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-monitor"
          size="mini"
          @click="showSplitScreenList">{{ $t('iot.splitScreenList') }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('common.number')" align="center" prop="id" />
      <el-table-column :label="$t('iot.customer')" align="center" prop="sysUser.nickName" />
      <el-table-column :label="$t('iot.project')" align="center" prop="faProject.projectname" />
      <el-table-column :label="$t('iot.lightPoleName')" align="center" prop="faLightpole.lightName" />
      <el-table-column :label="$t('iot.lightPoleNo')" align="center" prop="faLightpole.boxNo" />
      <el-table-column :label="$t('iot.videoMonitoring')" align="center" prop="faLightpole.ysNoun" show-overflow-tooltip>
        <template #default="scope">
          <el-button link @click="previewVideo(scope.row.faLightpole.ysNoun)"
            :disabled="scope.row.faLightpole && !scope.row.faLightpole.ysNoun" class="video-camera-button">
            <i class="el-icon-video-camera-solid"></i>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('iot.splitScreen')" align="center"  prop="faLightpole.SplitScreen" >
        <template #default="scope">
          <el-switch v-model="scope.row.moreswitch != 0"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            @change="handleSplitScreenChange(scope.row)">></el-switch>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.remark')" align="center" prop="remark" />
      <el-table-column :label="$t('common.createTime')" align="center" >
        <template slot-scope="scope">
          {{scope.row.createtime}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.status')" align="center" prop="faLightpole.status">
        <template #default="scope">
          <el-tag :type="scope.row.faLightpole && scope.row.faLightpole.status == '1' ? 'success' : 'danger'" disable-transitions>
            {{ scope.row.faLightpole && scope.row.faLightpole.status == '1' ? $t('map.online') : $t('map.offline') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:equipment:edit']">{{ $t('common.edit') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:equipment:remove']">{{ $t('common.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>
    <el-dialog
      :title="$t('iot.videoMonitoring')"
      :visible.sync="videoDialogVisible"
      width="800px"
      destroy-on-close>
      <div class="video-container">
        <video
          v-if="currentVideoUrl"
          :src="currentVideoUrl"
          controls
          class="preview-video">
        </video>
      </div>
      <!-- 添加方向控制按钮组 -->
      <div class="direction-controls">
        <div class="direction-grid">
          <el-button class="direction-btn" @click="handleDirection('leftUp')">
            <i class="el-icon-top-left"></i>
          </el-button>
          <el-button class="direction-btn" @click="handleDirection('up')">
            <i class="el-icon-top"></i>
          </el-button>
          <el-button class="direction-btn" @click="handleDirection('upright')">
            <i class="el-icon-top-right"></i>
          </el-button>
          <el-button class="direction-btn" @click="handleDirection('left')">
            <i class="el-icon-back"></i>
          </el-button>
          <el-button class="direction-btn center-btn" disabled>
            <i class="el-icon-aim"></i>
          </el-button>
          <el-button class="direction-btn" @click="handleDirection('right')">
            <i class="el-icon-right"></i>
          </el-button>
          <el-button class="direction-btn" @click="handleDirection('downleft')">
            <i class="el-icon-bottom-left"></i>
          </el-button>
          <el-button class="direction-btn" @click="handleDirection('down')">
            <i class="el-icon-bottom"></i>
          </el-button>
          <el-button class="direction-btn" @click="handleDirection('downright')">
            <i class="el-icon-bottom-right"></i>
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog :title="$t('iot.splitScreenDeviceList')" :visible.sync="splitScreenDialogVisible" width="80%" :fullscreen="true">
      <div :class="[splitScreenDevicesList.length !== 1　? 'split-screen-container' : 'split-screen-one-container']">
        <div v-for="(device,index) in splitScreenDevicesList" :key="index" class="video-item">
          <video :src="device.videoUrl" controls class="split-screen-video">{{ $t('iot.browserNotSupportVideo') }}</video>
        </div>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('iot.customerName')" prop="adminId">
          <el-select
            v-model="form.adminId"
            :placeholder="$t('iot.selectCustomer')"
            filterable
            style="width: 100%"
            @change="handleNicknameChanges">
            <el-option
              v-for="item in options"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('iot.projectName')" prop="projectId">
          <el-select
            v-model="form.projectId"
            :placeholder="$t('iot.selectProjectName')"
            filterable
            style="width: 100%"
            @change="handleProjectnameChanges">
            <el-option
              v-for="item in projectnameOptions"
              :key="item.id"
              :label="item.projectname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('iot.lightPoleNo')" prop="id">
          <el-select v-model="form.lightpoleId" :placeholder="$t('iot.selectLightPoleNo')" filterable style="width:100%" @change="handlelightpoleChange">
            <el-option v-for="item in lightpoleOptions" :key="item.id" :label="item.boxNo" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('common.enterRemark')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <el-row>
    </el-row>
  </div>
</template>
<script>
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment,getVideoUrl,getDeviceList,deviceControl } from "@/api/iot/equipment";
import { listProject } from '@/api/iot/faproject'
import { listUser } from '@/api/iot/tool'
import { options } from 'runjs'
import { listHgbox } from '@/api/iot/hgbox'
import { listLightpole } from '@/api/iot/lightpole'
import Template from '@/views/iot/template/index.vue'
export default {
  name: "Equipment",
  components: { Template },
  data() {
    return {
      clickVideoDeviceId:'',
      splitScreenDevicesList:[],
      deviceUrlList:[],
      splitScreenDialogVisible: false,
      splitScreenDevices: [],
      videoDialogVisible:false,
      currentVideoUrl:'',
      projectnameOptions: [],
      lightpoleOptions: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      equipmentList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminId: null,
        projectId: null,
        lightpoleId: null,
        type: null,
        json: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        vswitch: null,
        status: null,
        state: null,
        wifiname: null,
        wifipwd: null,
        moreswitch: null
      },
      form: {
        userId: null,
        nickName: '',
        projectname: '',
        projectId: null,
        id: null,
        lightName: '',
        lightpoleId: null,
        adminId: null,
      },
      rules: {}
    };
  },
  created() {
    this.getList();
    this.fetchProjectname();
    this.fetchNickname();
    this.fetchUser();
    this.fetchLightpole();
    setInterval(() => {
      this.getDeviceListInteval();
    },1000 * 60 * 3)
  },
  async mounted() {
    await this.fetchNickname();
    this.getList();
    await this.fetchLightpole();
  },
  methods: {
    handleDirection(direction) {
      console.log('direction:', direction);
      console.log(this.clickVideoDeviceId);
      let data = {command:direction,deviceId:this.clickVideoDeviceId};
      deviceControl(data).then(res => {}).catch(err => {})
    },
    async getDeviceMp4Url(ysNoun){
      try {
        const res= await getVideoUrl(ysNoun)
        let url = res.data.fmp4;
        return url;
      }catch (err){
        return "";
      }
    },
    async showSplitScreenList() {
      console.log("showSplitScreenList")
      console.log(this.splitScreenDevices)
      this.splitScreenDialogVisible = true;
      this.splitScreenDevicesList = await Promise.all(
        this.splitScreenDevices.map(async (device) => {
          const url = await this.getDeviceMp4Url(device);
          return {
            ysNoun: device,
            videoUrl: url
          };
        })
      );
    },
    removeSplitScreenDevice(index) {
      const removedDevice = this.splitScreenDevices[index];
      this.splitScreenDevices.splice(index, 1);
      this.equipmentList.forEach(item => {
        if (item.faLightpole && item.faLightpole.ysNoun === removedDevice) {
          item.faLightpole.SplitScreen = false;
        }
      });
    },
    handleSplitScreenChange(row) {
      if (row.faLightpole && row.faLightpole.ysNoun) {
        if (row.moreswitch != 1) {
          let param = {
            id:row.id,
            moreswitch : 1
          }
          updateEquipment(param).then(res => {
            this.getList();
            if (!this.splitScreenDevices.includes(row.faLightpole.ysNoun)) {
              this.splitScreenDevices.push(row.faLightpole.ysNoun);
            }
          })
        } else {
          let param = {
            id:row.id,
            moreswitch : 0
          }
          updateEquipment(param).then(res => {
            this.getList();
            const index = this.splitScreenDevices.indexOf(row.faLightpole.ysNoun);
            if (index > -1) {
              this.splitScreenDevices.splice(index, 1);
            }
          })
        }
        console.log('splitScreenDevices：', this.splitScreenDevices);
      }
    },
    getDeviceListInteval() {
      getDeviceList().then(res => {
        let deviceList = res
        if (this.equipmentList) {
          for (let i = 0; i < this.equipmentList.length; i++) {
            let item = this.equipmentList[i];
            for (let deviceListKey in deviceList) {
              let device = deviceList[deviceListKey]
              if (item.faLightpole) {
                let ysNoun = item.faLightpole.ysNoun;
                if (ysNoun.includes("/")) {
                  let ysNounArr = ysNoun.split("/")
                  console.log(typeof ysNounArr[0])
                  console.log(typeof device.deviceId)
                  if (ysNounArr[0] == device.deviceId) {
                    this.equipmentList[i].faLightpole.status = device.status;
                    break;
                  }
                }
              }
            }
          }
        }
      }).catch(err => {})},
    previewVideo(id){
      this.clickVideoDeviceId = id;
      getVideoUrl(id).then(res => {
        let url = res.data.fmp4;
        this.videoDialogVisible = true;
        this.currentVideoUrl = url;
      }).catch(err => {})},
    options,
    formatDate(timestamp) {
      const date = new Date(timestamp * 1000);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    async fetchLightpole() {
      try {
        const response = await listHgbox();
        if (response && response.rows && Array.isArray(response.rows)) {
          this.lightpoleOptions=response.rows.filter(item=>item.id&&item.boxNo).map(item=>({id:item.id,boxNo:item.boxNo,}));
        } else {
          console.error('error');
        }
      } catch (error) {
        console.error('error:', error);
      }
    },
    handlelightpoleChange(selectedId) {
      const selectedLightpole = this.lightpoleOptions.find(item => item.id === selectedId);
      if (selectedLightpole) {
        this.form.boxNo = selectedLightpole.boxNo;
        this.form.lightpoleId = selectedLightpole.id;
      } else {
      }
    },
    async fetchUser() {
      try {
        const response = await listUser();
        if (response && response.rows) {
          this.options = response.rows.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
        }
      } catch (error) {
        console.error('error', error);
      }
    },
    async fetchNickname() {
      try {
        const response = await listUser({});
        if (response && response.rows && Array.isArray(response.rows)) {
          this.options = response.rows.map(item => ({
            userId: item.userId,
            nickName: item.nickName
          }));
        } else {
          console.error('error');
        }
      } catch (error) {
        console.error('error:', error);
      }
    },
    handleNicknameChanges(selectedId) {
      const selectedOptions = this.options.find(option => option.userId === selectedId);
      if (selectedOptions) {
        this.form.nickName = selectedOptions.nickName;
        this.form.adminId = selectedOptions.userId;
      }
    },
    async fetchProjectname() {
      try {
        const response = await listProject({});
        if (response && Array.isArray(response.rows)) {
          this.projectnameOptions = response.rows.map(item => ({
            id: item.id,
            projectname: item.projectname,
          }));
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    handleProjectnameChanges(value) {
      const selectedDatas = this.projectnameOptions.find(option => option.id === value);
      if (selectedDatas) {
        this.form.projectname = selectedDatas.projectname;
        this.form.projectId = selectedDatas.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    getList() {
      this.loading = true;
      listEquipment(this.queryParams).then(response => {
        this.equipmentList = response.rows;
        console.log('equipmentList:', this.equipmentList);
        if (this.equipmentList) {
          for (let i = 0; i < this.equipmentList.length; i++) {
            let item = this.equipmentList[i];
            if (item.faLightpole) {
              this.$set(item.faLightpole, 'SplitScreen', false);
            }else{
              this.equipmentList[i].faLightpole = {SplitScreen:false};
            }
            if (item.faLightpole && item.faLightpole.ysNoun && item.moreswitch == 1) {
              if (!this.splitScreenDevices.includes(item.faLightpole.ysNoun)) {
                this.splitScreenDevices.push(item.faLightpole.ysNoun);
              }
            }
          }
        }
        this.total = response.total;
        this.loading = false;
      }).catch(err => {
        this.loading = false;
      })
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        adminId: null,
        projectId: null,
        lightpoleId: null,
        type: null,
        json: null,
        remark: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        vswitch: null,
        status: "1",
        state: null,
        wifiname: null,
        wifipwd: null,
        moreswitch: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    async handleAdd() {
      this.reset();
      await Promise.all([
        this.fetchNickname(),
        this.fetchProjectname(),
        this.fetchLightpole()
      ]);
      this.open = true;
      this.title = this.$t('iot.addDevice');
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEquipment(id).then(response => {
        console.log("response")
        console.log(response)
        this.form = response.data;
        this.form.nickName = response.data.sysUser.nickName;
        this.form.projectname = response.data.faProject.projectname;
        this.open = true;
        this.title = this.$t('iot.editDevice');
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEquipment(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('error', error);
              this.$message.error(this.$t('iot.updateDeviceFailed'));
            });
          } else {
            addEquipment(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('error:', error);
              this.$message.error(this.$t('iot.addDeviceFailed'));
            });
          }
        } else {
          this.$message.error(this.$t('iot.checkFormInput'));
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        this.$t('common.confirmDelete') + ' "' + ids + '" ' + this.$t('common.dataItem') + '？',
        this.$t('navbar.tip'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        return delEquipment(ids);
      }).then(() => {
        this.getList();
        this.$message({
          type: 'success',
          message: this.$t('common.deleteSuccess')
        });
      }).catch(() => {});
    },
    handleExport() {
      this.download('iot/equipment/export', {
        ...this.queryParams
      }, `equipment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.preview-video {
  max-height: 450px;
  object-fit: contain;
}
.video-camera-button {
  background-color: transparent !important;
  border: none;
  padding: 0;
}
.video-camera-button i {
  font-size: 24px;
}
.split-screen-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  padding: 20px;
  height: 500px;
}
.split-screen-one-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}
.video-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  height: inherit;
  width: inherit;
}
.video-header {
  padding: 10px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.split-screen-video {
  width: 100%;
  height: 500px;
  object-fit: cover;
}
.split-screen-container:has(.video-item:only-child) .video-item {
  grid-column: 1 / -1;
}
.split-screen-container:has(.video-item:only-child) .split-screen-video {
  height: calc(100vh - 200px);
}
.direction-controls {
  margin-top: 20px;
  display: flex;
  justify-content: start;
}
.direction-grid {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  width: 200px;
  background-color: #f5f7fa;
  border-radius: 8px;
}
.direction-btn {
  width: 50px;
  height: 50px;
  padding: 0;
  margin: 5px;
  border: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  border-radius: 4px;
}
.direction-btn i {
  font-size: 18px;
  line-height: 1;
}
.direction-btn:hover {
  background-color: #ecf5ff;
  border-color: #409eff;
}
.direction-btn:active {
  background-color: #409eff;
  color: white;
}
.center-btn {
  background-color: #f5f7fa !important;
  border-color: #dcdfe6 !important;
  cursor: not-allowed;
}
.center-btn i {
  font-size: 20px;
  color: #909399;
}
</style>
